package com.srd.phone.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.VolleyError;
import com.shengrongdai.srd.R;
import com.srd.phone.adapter.MessAdapter;
import com.srd.phone.bean.MessageBean;
import com.srd.phone.mvp.presenters.UtilPresenter;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.swipe.PullToRefreshView;
import com.srd.phone.utils.swipe.SwipeMenu;
import com.srd.phone.utils.swipe.SwipeMenuCreator;
import com.srd.phone.utils.swipe.SwipeMenuItem;
import com.srd.phone.utils.swipe.SwipeMenuListView;
import com.srd.phone.utils.wheel.widget.DialogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息列表
 * */
public class MesListActivity extends BaseActivity implements View.OnClickListener{

    private SwipeMenuListView mListView = null;
    private MessAdapter adapter = null;

    private List<MessageBean> mList = new ArrayList<>();
    private PullToRefreshView mPullToRefreshView;
    private UtilPresenter utilPresenter = null;
    private int currentPage = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        initView();
        initData();
    }

    @Override
    public void initView(){
        super.initView();

        tv_common_title.setText("消息中心");
        tv_common_right.setVisibility(View.VISIBLE);
        tv_common_right.setText("清空");
        tv_common_right.setOnClickListener(this);

        mPullToRefreshView = (PullToRefreshView)findViewById(R.id.pull_refresh_view);
        mListView = (SwipeMenuListView)findViewById(R.id.listview);

        adapter = new MessAdapter(this, mList);
        mListView.setAdapter(adapter);

    }

    private int mPosition = 0;

    @Override
    public void initData() {
        super.initData();

        showWaitingDialog();
        presenter = new UtilPresenter(requestQueue, this);
        utilPresenter = (UtilPresenter)presenter;
        setUrlArrs(Constants.MESSAGE_LIST, Constants.MESSAGE_DEL, Constants.MESSAGE_UPDATE);


        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                deleteItem.setWidth(dp2px(90));
                deleteItem.setIcon(R.mipmap.ic_delete);
                menu.addMenuItem(deleteItem);

            }
        };
        mListView.setMenuCreator(creator);

        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                MessageBean item = adapter.getItem(position);
                switch (index) {
                    case 0:
                        mPosition = position;
                        delData(item.id + ",");
                        break;
                }
                return false;
            }
        });


        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MessageBean item = adapter.getItem(position);
                Intent intent = new Intent(MesListActivity.this, MesListInfoActivity.class);
                intent.putExtra("title", item.title);
                intent.putExtra("date", item.ctime);
                intent.putExtra("info", item.content);
                gotoActivity(intent);

                if (item.state == 85) {
                    utilPresenter.singleParam(Constants.MESSAGE_UPDATE, "ids", String.valueOf(item.id));
                    item.state = 84;
                    mList.set(position, item);
                    adapter.setData(mList);
                }
            }
        });


        mPullToRefreshView.setOnFooterRefreshListener(new PullToRefreshView.OnFooterRefreshListener() {
            @Override
            public void onFooterRefresh(PullToRefreshView view) {
                getData();
            }
        });

        mPullToRefreshView.setOnHeaderRefreshListener(new PullToRefreshView.OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(PullToRefreshView view) {
                currentPage = 1;
                getData();
            }
        });

        getData();
    }

    private void getData(){
        utilPresenter.requestData(Constants.MESSAGE_LIST, currentPage);
    }

    private void delData(String ids){
        utilPresenter.singleParam(Constants.MESSAGE_DEL, "ids", ids);
    }

    @Override
    public void returnData(String tag, String data) {
        super.returnData(tag, data);
        complete();
        if(Constants.MESSAGE_LIST.equals(tag)){
            if(currentPage == 1) mList.clear();
            List<MessageBean> list = MessageBean.parseData(data);
            if(list == null || list.size() == 0){
                toastShow("没有更多数据~");
                return;
            }
            currentPage += 1;
            mList.addAll(list);
            adapter.setData(mList);
        }else if(Constants.MESSAGE_DEL.equals(tag)){
            try {
                JSONObject jsonObj = new JSONObject(data);
                String message = jsonObj.optString("message");
                toastShow(message);

                if(message.equals("删除成功")){
                    if(mPosition == -1)
                        mList.clear();
                    else
                        mList.remove(mPosition);
                    adapter.setData(mList);

                    mPosition = 0;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String tag, VolleyError error) {
        super.onError(tag, error);
        complete();
    }

    private void complete(){
        cancelWaitingDialog();
        mPullToRefreshView.onHeaderRefreshComplete();
        mPullToRefreshView.onFooterRefreshComplete();
    }

    private int getLayoutId(){
        return R.layout.activity_message_list;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.tv_common_right:
                new DialogUtil(MesListActivity.this, new DialogUtil.CallBack() {
                    @Override
                    public void onClick() {
                        mPosition = -1;
                        delData(getAllItemIds());
                    }
                });
                break;
        }
    }

    private String getAllItemIds(){
        StringBuffer sb = new StringBuffer();
        for (MessageBean bean : mList){
            sb.append(bean.id + ",");
        }
        return sb.toString();
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }
}

